package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类
 *
 * @param
 * @return
 * @author heiheiheng
 * @create 2025/8/12
 **/
@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 每分钟检查一次是否有超时未支付的订单
     * 
     * @return 
     * @author heiheiheng
     * @create 2025/8/12
     **/
    @Scheduled(cron = "0 0/1 * * * ?")
    public void processOutTimeOrder(){
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        if (ordersList !=null && ordersList.size()>0){
            ordersList.forEach(x ->{
                x.setStatus(Orders.CANCELLED);
                x.setCancelTime(LocalDateTime.now());
                x.setCancelReason("订单超时，自动取消");
                ordersMapper.update(x);
            });
        }
    }

    /**
     * 每天凌晨一点检查一次订单表，查看是否有派送中的状态，如果存在改为已完成
     *
     * @return
     * @author heiheiheng
     * @create 2025/8/12
     **/
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList !=null && ordersList.size()>0){
            ordersList.forEach(x ->{
                x.setStatus(Orders.COMPLETED);
                x.setDeliveryTime(LocalDateTime.now().minusHours(1));
                ordersMapper.update(x);
            });
        }
    }
}
